package pri.syl.xiaowu.websocket.netty.server.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.TimeUnit;

/**
 * ClassName: HttpServerInitChannelHandler
 * Description: 初始化netty通道
 */
@Getter
@Setter
public class HttpServerInitChannelHandler extends ChannelInitializer<SocketChannel> {
    private int httpReaderIdleTime;
    private int httpWriterIdleTime;
    private int httpAllIdleTime;
    private int httpMaxContentLength;
    private int websocketMaxFramePayloadLength;
    private int websocketReadTimeoutMilli;

    public HttpServerInitChannelHandler(int httpReaderIdleTime, int httpWriterIdleTime, int httpAllIdleTime, int httpMaxContentLength, int websocketMaxFramePayloadLength, int websocketReadTimeoutMilli) {
        this.httpReaderIdleTime = httpReaderIdleTime;
        this.httpWriterIdleTime = httpWriterIdleTime;
        this.httpAllIdleTime = httpAllIdleTime;
        this.httpMaxContentLength = httpMaxContentLength;
        this.websocketMaxFramePayloadLength = websocketMaxFramePayloadLength;
        this.websocketReadTimeoutMilli = websocketReadTimeoutMilli;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        //初始化空闲状态
        ch.pipeline().addLast(new IdleStateHandler(httpReaderIdleTime, httpWriterIdleTime, httpAllIdleTime, TimeUnit.MILLISECONDS))
                //添加http编码器
                .addLast(new HttpServerCodec())
                //增加块状读取
                .addLast(new HttpObjectAggregator(httpMaxContentLength))
                //请求处理
                .addLast(new HttpServerHandler(websocketMaxFramePayloadLength, websocketReadTimeoutMilli));
    }
}
